import { Controller } from '@nestjs/common';
import { IpcHandle, Window } from '@doubleshot/nest-electron';
import { Payload } from '@nestjs/microservices';
import { type Observable, of } from 'rxjs';
import type { BrowserWindow } from 'electron';
import { IpcService } from './ipc.service';

@Controller()
export class IpcController {
  constructor(
    private readonly ipcService: IpcService,
    @Window() private readonly mainWin: BrowserWindow
  ) {}

  @IpcHandle('getMac')
  public getMac() {
    return this.ipcService.getMac();
  }

  @IpcHandle('setConfig')
  public setConfig(
    data = {
      host: 'localhost',
      syncHostSqlite: false,
    }
  ) {
    return this.ipcService.setConfig(data);
  }

  @IpcHandle('reload')
  public reload() {
    return this.ipcService.reload();
  }

  @IpcHandle('plcConnect')
  public plcConnect(data) {
    return this.ipcService.plcConnect(data);
  }

  @IpcHandle('deleteChildProcess')
  public deleteChildProcess() {
    return this.ipcService.deleteChildProcess();
  }

  @IpcHandle('msg')
  public handleSendMsg(@Payload() msg: string): Observable<string> {
    const { webContents } = this.mainWin;
    webContents.send('reply-msg', 'this is msg from webContents.send');
    return of(
      `The main process received your message: ${msg} at time: ${this.ipcService.getTime()}`
    );
  }

  public emitWinMsg(event, data) {
    const { webContents } = this.mainWin;

    webContents.send(event, data);
  }
}
